package net.hiwii.db.bind.sub;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;
import com.sleepycat.je.DatabaseException;

import net.hiwii.arg.Argument;
import net.hiwii.db.ent.StoredValue;
import net.hiwii.state.sub.SubjectFunctionStatement;
import net.hiwii.system.exception.ApplicationException;
import net.hiwii.system.util.EntityUtil;
import net.hiwii.view.HObject;

public class SubjectFunctionStatementBinding extends TupleBinding<SubjectFunctionStatement> {

	@Override
	public SubjectFunctionStatement entryToObject(TupleInput arg0) {
		SubjectFunctionStatement ff = new SubjectFunctionStatement();
		
		try {
			String type = arg0.readString();
			String val = arg0.readString();
			StoredValue sv0 = new StoredValue();
			sv0.setType(type);
			sv0.setValue(val);
			HObject value = EntityUtil.recordToEntity(sv0);
			ff.setSubject(value);
			
			String name = arg0.readString();
			ff.setName(name);
			boolean pos = arg0.readBoolean();
			ff.setPositive(pos);
			
			int num = arg0.readInt();
			List<HObject> list = new ArrayList<HObject>();
			for(int n=0;n<num;n++){
				String ty = arg0.readString();
				String v = arg0.readString();
				StoredValue sv = new StoredValue();
				sv.setType(ty);
				sv.setValue(v);
				HObject ent = EntityUtil.recordToEntity(sv);
				list.add(ent);
			}
			ff.setArguments(list);
			return ff;
		} catch (IndexOutOfBoundsException e) {
			return null;
		} catch (IllegalArgumentException e) {
			return null;
		} catch (DatabaseException e) {
			return null;
		} catch (IOException e) {
			return null;
		} catch (ApplicationException e) {
			return null;
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public void objectToEntry(SubjectFunctionStatement arg0, TupleOutput arg1) {
		try {
			StoredValue val = EntityUtil.entityToRecord(arg0.getSubject());
			arg1.writeString(val.getType());
			arg1.writeString(val.getValue());
			
			arg1.writeString(arg0.getName());
			arg1.writeBoolean(arg0.isPositive());
			arg1.writeInt(arg0.getArguments().size());
			for(int i=0;i<arg0.getArguments().size();i++) {
				StoredValue sv = EntityUtil.entityToRecord(arg0.getArguments().get(i));
				arg1.writeString(sv.getType());
				arg1.writeString(sv.getValue());
			}
		} catch (ApplicationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
